#include <rtthread.h>
#include <lwip/sockets.h>

#define BUFSZ	1024

extern void led(rt_uint32_t led, rt_uint32_t value);

void udpsrv(void* paramemter)
{
   int sock;
   int bytes_read;
   char *recv_data;
   rt_uint32_t addr_len;
   struct sockaddr_in server_addr, client_addr;

   recv_data = rt_malloc(BUFSZ);
   if (recv_data == RT_NULL)
   {
       rt_kprintf("No memory\n");
       return;
   }

   if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
   {
       rt_kprintf("Socket error\n");
	   
       rt_free(recv_data);
       return;
   }
   
   server_addr.sin_family = AF_INET;
   server_addr.sin_port = htons(9090);
   server_addr.sin_addr.s_addr = INADDR_ANY;
   rt_memset(&(server_addr.sin_zero),0, sizeof(server_addr.sin_zero));

   if (bind(sock,(struct sockaddr *)&server_addr,
            sizeof(struct sockaddr)) == -1)
   {

       rt_kprintf("Bind error\n");

       rt_free(recv_data);
       return;
   }

   addr_len = sizeof(struct sockaddr);
   rt_kprintf("UDPServer Waiting for client on port 9090...\n");

   while (1)
   {
       bytes_read = recvfrom(sock, recv_data, BUFSZ - 1, 0,
                             (struct sockaddr *)&client_addr, &addr_len);
 

       recv_data[bytes_read] = '\0'; 

       rt_kprintf("\n(%s , %d) said : ",inet_ntoa(client_addr.sin_addr),
                  ntohs(client_addr.sin_port));
       rt_kprintf("%s", recv_data);


       if (strcmp(recv_data, "exit") == 0)
       {
           lwip_close(sock);

           rt_free(recv_data);
           break;
       }
	   else if (strncmp(recv_data, "ledon", 5) == 0)
	   {
			led(0, 1);
	   }
	   else if (strncmp(recv_data, "ledoff", 6) == 0)
	   {
			led(0, 0);
	   }
	 }

   return;
}
